<template>
    <div class="filter-container">
        <div class="filter-header">
            <h2>题目列表</h2>
        </div>

        <div class="filter-options">
            <div class="filter-row">
                <!-- 搜索框部分 -->
                <div class="search-wrapper">
                    <el-popover v-model:visible="searchPopoverVisible" trigger="click" placement="bottom-start"
                        :width="300">
                        <template #reference>
                            <div class="search-trigger">
                                <el-icon>
                                    <Search />
                                </el-icon>
                                <span>{{ searchText || '搜索题目' }}</span>
                                <el-icon class="el-icon--right"><arrow-down /></el-icon>
                            </div>
                        </template>
                        <div class="search-popover">
                            <el-input v-model="searchText" placeholder="输入关键词搜索题目" clearable @clear="handleClear"
                                class="search-input" size="large">
                                <template #prefix>
                                    <el-icon class="search-icon">
                                        <Search />
                                    </el-icon>
                                </template>
                                <template #append>
                                    <el-button type="primary" @click="handleSearch" class="search-button">
                                        搜索
                                    </el-button>
                                </template>
                            </el-input>
                        </div>
                    </el-popover>
                </div>

                <!-- 在搜索框后添加题目类型下拉框 -->
                <el-dropdown trigger="click" @command="handleTypeChange">
                    <span class="dropdown-link">
                        {{ currentType || '题目类型' }}
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="单选">单选</el-dropdown-item>
                            <el-dropdown-item command="多选">多选</el-dropdown-item>
                            <el-dropdown-item command="判断">判断</el-dropdown-item>
                            <el-dropdown-item command="简答">简答</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>


                <!-- 题目难度 -->
                <el-dropdown trigger="click" @command="handleDifficultyChange">
                    <span class="dropdown-link">
                        {{ currentDifficulty }}
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="简单">简单</el-dropdown-item>
                            <el-dropdown-item command="中等">中等</el-dropdown-item>
                            <el-dropdown-item command="困难">困难</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>

                <!-- 添加得分选择下拉框 -->
                <el-dropdown trigger="click" @command="handleScoreChange">
                    <span class="dropdown-link">
                        {{ currentScore || '得分' }}
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="2">2分</el-dropdown-item>
                            <el-dropdown-item command="4">4分</el-dropdown-item>
                            <el-dropdown-item command="6">6分</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>

                <!-- 二级分类选择 -->
                <div class="tag-select">
                    <el-select v-model="selectedTags" filterable placeholder="二级分类选择" clearable>
                        <el-option v-for="category in subCategories" :key="category.id" :value="category.id"
                            :label="category.categoryName" />
                    </el-select>
                </div>

                <!-- 添加重置按钮 -->
                <el-button @click="handleReset" :loading="isResetting">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    重置
                </el-button>

            </div>

        </div>

    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ArrowDown, Search, Refresh } from '@element-plus/icons-vue'  // 添加 Refresh 图标
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
import { useTopicStores } from '@/stores/topicStores'



// 修改难度值的映射
const difficultyMap: { [key: string]: number } = {
    '简单': 1,
    '中等': 2,
    '困难': 3
}

// 添加题目类型映射
const typeMap: { [key: string]: number } = {
    '单选': 1,
    '多选': 2,
    '判断': 3,
    '简答': 4
}

const route = useRoute();
const current_category_id = Number(route.query.category_id);

// 添加题目类型相关的 ref
const currentType = ref < string > ('题目类型')

// 添加得分相关的 ref
const currentScore = ref('得分')
const topicStore = useTopicStores();
const { getCurrentSubject } = topicStore;
const { subCategories,currentSubjectList } = storeToRefs(topicStore)

const searchPopoverVisible = ref(false)
const searchText = ref('')
const currentDifficulty = ref('难度')
const selectedTags = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 添加一个标志位来控制是否触发 watch
const isResetting = ref(false)
const skipNextWatch = ref(false)


// 添加搜索方法
const handleSearch = async (...condition: any) => {
    const params = {
        type: currentType.value !== '题目类型' ? typeMap[currentType.value] : null, // 默认为简答题
        detail: searchText.value,
        difficult: currentDifficulty.value !== '难度' ? difficultyMap[currentDifficulty.value] : null,
        categoryIdList: selectedTags.value ? [current_category_id, selectedTags.value] : [current_category_id],
        labelIdList: [],
        score: currentScore.value !== '得分' ? Number(currentScore.value) : null,
        ...condition
    }
    
    try {
        await getCurrentSubject(params, currentPage.value, pageSize.value);
        // 发送事件通知父组件更新题目列表
        emit('search-result', {data:currentSubjectList.value,  params });
        searchPopoverVisible.value = false
    } catch (error) {
        console.error('搜索失败：', error)
        ElMessage.error('搜索失败，请重试')
    }
}

// 清除搜索条件
const handleClear = () => {
    searchText.value = ''
    currentDifficulty.value = '难度'
    selectedTags.value = ''
    handleSearch() // 清除后重新搜索
}

// 添加得分变更处理函数
const handleScoreChange = (command: any) => {
    currentScore.value = command
}

// 添加题目类型变更处理函数
const handleTypeChange = (command: any) => {
    currentType.value = command
}



// 修改重置函数，添加题目类型重置
const handleReset = async () => {
    try {
        isResetting.value = true
        skipNextWatch.value = true

        // 重置所有筛选条件
        searchText.value = ''
        currentDifficulty.value = '难度'
        selectedTags.value = ''
        currentScore.value = '得分'
        currentType.value = '题目类型' // 添加题目类型重置

        await handleSearch()
        ElMessage.success('已重置所有筛选条件')
    } finally {
        isResetting.value = false
        skipNextWatch.value = false
    }
}

// 修改 watch，添加题目类型监听
watch([currentDifficulty, selectedTags, currentScore, currentType], () => {
    if (!skipNextWatch.value) {
        handleSearch()
    }
})

// 定义事件
const emit = defineEmits(['search-result'])

const handleDifficultyChange = (command:any) => {
    currentDifficulty.value = command
}

</script>

<style scoped>
.filter-container {
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-header {
    margin-bottom: 20px;
}

.filter-options {
    margin-bottom: 20px;
}

.filter-row {
    display: flex;
    align-items: center;
    gap: 20px;
}

.dropdown-link {
    cursor: pointer;
    display: flex;
    align-items: center;
    color: #606266;
}

.tag-select {
    flex: 1;
}

:deep(.el-select) {
    width: 100%;
}

.search-wrapper {
    position: relative;
}

.search-trigger {
    cursor: pointer;
    padding: 8px 16px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #606266;
    transition: all 0.3s;
    min-width: 200px;
}

.search-trigger:hover {
    border-color: #409eff;
    color: #409eff;
}


.search-popover {
    padding: 12px;
    background-color: #fff;
}

.search-input {
    width: 100%;
}

.search-input :deep(.el-input__wrapper) {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border-radius: 6px;
    padding: 4px 8px;
    transition: all 0.3s;
}

.search-input :deep(.el-input__wrapper:hover) {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.search-input :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #409eff;
}

.search-icon {
    font-size: 16px;
    color: #909399;
}

.search-button {
    height: 100%;
    border-radius: 0 6px 6px 0;
    padding: 0 20px;
    font-size: 14px;
    background-color: #409eff;
    /* 添加背景色 */
    color: white;
    /* 添加文字颜色 */
    border: none;
    /* 移除边框 */
    transition: all 0.3s;
    /* 添加过渡效果 */
}

.search-button:hover {
    /* 添加悬停效果 */
    background-color: #66b1ff;
}

:deep(.el-input-group__append) {
    padding: 0;
    border: none;
    background-color: transparent;
    /* 确保附加组件背景透明 */
}

/* 可选：调整下拉框间距和响应式布局 */
.filter-row {
    display: flex;
    align-items: center;
    gap: 16px;
    /* 减小间距使布局更紧凑 */
    flex-wrap: wrap;
}

.dropdown-link {
    min-width: 90px;
    /* 确保下拉框有足够宽度显示文字 */
    text-align: center;
}
</style>